import router from '@system.router';
import usbManager from '@ohos.usbManager';
// import usbManager from '@kit.BasicServicesKit';
import CheckEmptyUtils from '../../utils/CheckEmptyUtils.js';
import FileUtils from '../../utils/FileUtils.js';
import DateUtils from '../../utils/DateAndTimeUtil.js';
import EventConstants from '../../utils/EventConstants.js';
//import parameter from '@ohos.systemparameter';
import prompt from '@system.prompt';

export default {
    data: {
        result: 'World',
        device: null,
        config: null,
        pip: null,
        inEndpoint: null,
        outEndpoint: null,
        interface: null,
        usbRequest: null,
        sendData: "",
        isClaimed: false,
        maxInSize: 1024,
        maxOutSize: 1024,
        beginTime: 0,
        beginTimeRe: 0,
        endTime: 0,
        endTimeRe: 0,
        executionTime: 0,
        timeDifference: 0,
        totalCount: 0,
        successCount: 0,
        isSending: false,
        index: 0,
        deviceName: ""
    },
    onInit() {
        this.index = this.indexParam;
        console.info("usb transfer device index : " + this.index);
        this.initData();
    },
    initData() {
        var deviceList = usbManager.getDevices();
        if (CheckEmptyUtils.isEmptyArr(deviceList)) {
            this.result = "init error ： 设备列表为空";
            console.info("usb device is null");
            return;
        }
        let name = this.index + 1;
        if (deviceList.length - 1 < this.index) {
            this.result = "error ： 未插入设备" + name;
            console.info("usb device size is : " + deviceList.length);
            console.info("usb open index is : " + this.index);
            return;
        }
        this.device = deviceList[this.index];
        console.info("usb connectDevice device: " + JSON.stringify(this.device));
        this.deviceName = "设备" + name + " : " + this.device.name;
        try {
            this.pip = usbManager.connectDevice(this.device);
            if (CheckEmptyUtils.isEmpty(this.pip)) {
                this.result = "opendevice faild";
                console.info("usb opendevice pip is null");
                return;
            }
        } catch (err) {
            this.result = "设备打开失败：" + err;
            console.info("usb 设备打开失败：" + err);
            return;
        }

        console.info("usb connect back pip: " + JSON.stringify(this.pip));
        if (CheckEmptyUtils.isEmptyArr(this.device.configs)) {
            this.result = "init error ： 设备configs列表为空";
            console.info("usb request configs is null");
            return;
        }
        this.config = this.device.configs[0]

        console.info("usb request this.config: " + JSON.stringify(this.config));

        if (CheckEmptyUtils.isEmptyArr(this.config.interfaces)) {
            this.result = "init error ： 设备interfaces列表为空";
            console.info("usb request interfaces is null");
            return;
        }
        var interfaceSize = this.config.interfaces.length;
        console.info("usb request this.interface size: " + interfaceSize);

        for (let i = 0; i < interfaceSize; i++) {
            this.interface = this.config.interfaces[i];
            if (CheckEmptyUtils.isEmptyArr(this.interface.endpoints)) {
                continue;
            }
            // acm interface
            if (this.interface.clazz != 10 || this.interface.subClass!= 0 || this.interface.protocol != 2) {
                continue;
            }
            // transfer endpoint
            for (let k = 0, len = this.interface.endpoints.length; k < len; k++) {
                let endpoint = this.interface.endpoints[k];
                if (endpoint.type == EventConstants.USB_ENDPOINT_XFER_BULK) {
                    if (endpoint.direction == EventConstants.USB_ENDPOINT_DIR_OUT) {
                        this.outEndpoint = endpoint;
                        this.maxOutSize = endpoint.maxPacketSize;
                    } else if (endpoint.direction == EventConstants.USB_ENDPOINT_DIR_IN) {
                        this.inEndpoint = endpoint
                        this.maxInSize = endpoint.maxPacketSize;
                    }
                }
            }

            if (!CheckEmptyUtils.isEmpty(this.outEndpoint) && !CheckEmptyUtils.isEmpty(this.inEndpoint)) {
                break;
            } else {
                this.outEndpoint = null;
                this.inEndpoint = null
            }
        }

        if (CheckEmptyUtils.isEmpty(this.outEndpoint) || CheckEmptyUtils.isEmpty(this.inEndpoint)) {
            console.info("usb init failed, outEndpoint or inEndpoint is null");
            return;
        }

        console.info("usb request outEndpoint: " + JSON.stringify(this.outEndpoint));
        console.info("usb request inEndpoint: " + JSON.stringify(this.inEndpoint));

        this.isClaimed = usbManager.claimInterface(this.pip, this.interface, true) == 0;
        console.info("usb request,claimInterface " + this.isClaimed);
        if (!this.isClaimed) {
            this.result = "init error ： claimInterface failed";
        }
    },
    readData() {
        if (CheckEmptyUtils.isEmpty(this.pip)) {
            this.result = "read error ： 设备this.pip为空";
            console.info("usb request,readData pip is null");
            return;
        }

        if (CheckEmptyUtils.isEmpty(this.inEndpoint)) {
            this.result = "read error ： 设备this.inEndpoint为空";
            console.info("usb request,readData inEndpoint is null");
            return;
        }

        if (!this.isClaimed) {
            this.result = "readData error ： claimInterface failed";
            console.info("usb request,readData claimInterface failed");
            return;
        }

        var tmpUint8Array = new Uint8Array(this.maxInSize);
        usbManager.bulkTransfer(this.pip, this.inEndpoint, tmpUint8Array, 15000).then(dataLength => {
            if (dataLength >= 0) {
                console.info("usb readData result Length : " + dataLength);
                console.info("usb buffer : " + tmpUint8Array);
                var resultStr = this.ab2str(tmpUint8Array);
                console.info("usb readData buffer : " + resultStr);
                this.result = "readData ab2str result ：" + resultStr;
            } else {
                console.info("usb readData failed : " + dataLength);
                this.result = "readData failed : " + dataLength;
            }
            console.info("usb readData end------------------------");
        }).catch(error => {
            this.result = "readData error ：" + JSON.stringify(error);
            console.info("usb readData error : " + JSON.stringify(error));
        });
    },
    getPropData() {
        let info = "default";
//        try {
//            info = parameter.getSync("test_usb", "default");
//            console.log("usb parameter " + JSON.stringify(info));
//        } catch (e) {
//            console.log("usb parameter getSync unexpected error: " + e);
//        }
        return info;
    },
    writeData_param() {
        var data = this.getPropData();
        console.info("usb write sendData： " + data);
        this.writeData(data);
    },
    writeData_time() {
        this.writeData("send time " + (new DateUtils()).nowWithSeconds());
    },
    writeData24() {
        if (CheckEmptyUtils.isEmpty(this.pip)) {
            this.result = "write error ： 设备this.pip为空";
            console.info("usb request,writeData pip is null");
            return;
        }
        if (CheckEmptyUtils.isEmpty(this.outEndpoint)) {
            this.result = "write error ： 设备this.outEndpoint为空";
            console.info("usb request,writeData outEndpoint is null");
            return;
        }
        if (!this.isClaimed) {
            this.result = "write error ： claimInterface failed";
            console.info("usb request,write claimInterface failed");
            return;
        }
        if (this.isSending) {
            prompt.showToast({
                message: "已经开始发送了。。。",
                duration: 5000
            });
            return;
        }
        this.isSending = true;
        this.beginTime = (new Date()).getTime();
        this.beginTimeRe = this.getLocalTime(this.beginTime);
        this.totalCount = 0;
        this.successCount = 0;
        this.transfer();
        //        var beginTime = (new Date()).getTime();
        //        var endTime = (new Date()).getTime();
        //        console.info("usb writeData24 begin");
        //        //1000*60*60*12 43200000
        //        while(endTime - beginTime < 10000) {
        //            var testData = "send milliseconds " + endTime;
        //            var tmpUint8Array = this.str2ab(testData);
        //            console.info("usb writeData24 : " + testData);
        //            usb.bulkTransfer(this.pip, this.outEndpoint, tmpUint8Array, 15000).then(dataLength => {
        //                if (dataLength >= 0) {
        //                    console.info("usb writeData result write length : " + dataLength);
        //                    this.result = "writeData success, write length : " + dataLength;
        //                } else {
        //                    this.result = "writeData failed";
        //                }
        //            }).catch(error => {
        //                this.result = "writeData error ：" + JSON.stringify(error);
        //                console.info("usb writeData error : " + JSON.stringify(error));
        //            });
        //            endTime = (new Date()).getTime();
        //        }
    },
    transfer() {
        if (this.beginTime == 0) {
            this.isSending = false;
            return;
        }
        this.isSending = true;
        this.totalCount = this.totalCount + 1;
        var testData = "send milliseconds " + (new Date()).getTime();
        var tmpUint8Array = new Uint8Array(512).fill(73);
        console.info("usb writeData24 : " + testData);
        usbManager.bulkTransfer(this.pip, this.outEndpoint, tmpUint8Array, 15000).then(dataLength => {
            if (dataLength >= 0) {
                console.info("usb writeData result write length : " + dataLength);
            } else {
                console.info("writeData failed");
            }
            this.successCount = this.successCount + 1;
            this.result = "writeData24 total ：" + this.totalCount + " ; success:" + this.successCount;
            this.transfer();
        }).catch(error => {
            this.result = "writeData error ：" + JSON.stringify(error);
            console.info("usb writeData error : " + JSON.stringify(error));
            this.endTime = (new Date()).getTime();
            this.endTimeRe = this.getLocalTime((new Date()).getTime());
            this.timeDifference = this.endTime - this.beginTime;
            this.getTimeDifference(this.timeDifference);
            // this.transfer();
        });
    },
    stopTransfer() {
        this.endTime = (new Date()).getTime();
        this.endTimeRe = this.getLocalTime(this.endTime);
        this.timeDifference = this.endTime - this.beginTime;
        this.getTimeDifference(this.timeDifference);
        this.beginTime = 0;
        prompt.showToast({
            message: "停止发送。。。",
            duration: 5000
        });
    },
    writeData(dataToSend) {
        if (CheckEmptyUtils.isEmpty(this.pip)) {
            this.result = "write error ： 设备this.pip为空";
            console.info("usb request,writeData pip is null");
            return;
        }
        if (CheckEmptyUtils.isEmpty(this.outEndpoint)) {
            this.result = "write error ： 设备this.outEndpoint为空";
            console.info("usb request,writeData outEndpoint is null");
            return;
        }
        if (!this.isClaimed) {
            this.result = "write error ： claimInterface failed";
            console.info("usb request,write claimInterface failed");
            return;
        }

        console.info("usb writeData begin");

        var tmpUint8Array = this.str2ab(dataToSend);
        console.info("usb writeData byteLength : " + tmpUint8Array.byteLength);
        usbManager.bulkTransfer(this.pip, this.outEndpoint, tmpUint8Array, 15000).then(dataLength => {
            if (dataLength >= 0) {
                console.info("usb writeData result write length : " + dataLength);
                this.result = "writeData success, write length : " + dataLength;
            } else {
                this.result = "writeData failed";
            }

        }).catch(error => {
            this.result = "writeData error ：" + JSON.stringify(error);
            console.info("usb writeData error : " + JSON.stringify(error));
        });
    },
    sendControl() {
        if (CheckEmptyUtils.isEmpty(this.pip)) {
            this.result = "write error ： 设备this.pip为空";
            console.info("usb request,writeData pip is null");
            return;
        }

        console.info("usb writeData begin");
        var tmpUint8Array = new Uint8Array(255);
        //        controlTransfer(pipe: UsbDevicePipe, requestType: number, request: number, value: number, index: number,
        //                             buffer: Uint8Array, length: number, timeout: number): number;
        //
        var requestCmd = 6;
        var requestType = ((1 << 7) | (0 << 5) | (0 & 0x1f));
        //int32_t value = (1 << 8) + 0; // descriptor type << 8 + descriptor index
        var value = (2 << 8) + 0; // descriptor type << 8 + descriptor index
        var index = 0;
        var timeout = 5000;
        var controlParam = {
            request: requestCmd,
            reqType: requestType,
            value: value,
            index: index,
            data: tmpUint8Array
        };
        var stringParam = "request:" + controlParam.request + ", reqType:"
        + controlParam.reqType + ", value:" + controlParam.value + ", index:" + controlParam.index;
        usbManager.controlTransfer(this.pip, controlParam, timeout).then(dataLength => {
            console.info("usb controlTransfer buffer length : " + dataLength);
            console.info("usb controlTransfer data : " + controlParam.data);
            let dataResult;
            if (dataLength > 0) {
                dataResult = controlParam.data.subarray(0, dataLength - 1);
            }
            this.result = "控制命令 [" + stringParam + "] 传输成功: \n接收到返回的内容：" + dataResult;
        }).catch(error => {
            this.result = "控制命令传输失败：" + JSON.stringify(error);
            console.info("usb controlTransfer error : " + JSON.stringify(error));
        });
    },
    onBackPress() {
        if (CheckEmptyUtils.isEmpty(this.pip)) {
            return;
        }
        if (this.isClaimed) {
            let releaseStatus = usbManager.releaseInterface(this.pip, this.interface);
            console.info("usb request,releaseInterface : " + releaseStatus);
        }
        var isPipClose = usbManager.closePipe(this.pip);
        console.info("usb request,PipClose : " + isPipClose);
        router.back();
    },
// ArrayBuffer转为字符串，参数为ArrayBuffer对象
    ab2str(buf) {
        return String.fromCharCode.apply(null, new Uint8Array(buf));
    },

// 字符串转为ArrayBuffer对象，参数为字符串
    str2ab(str) {
        var arr = [];
        for (var i = 0, j = str.length; i < j; ++i) {
            arr.push(str.charCodeAt(i));
        }
        var tmpUint8Array = new Uint8Array(arr);
        return tmpUint8Array;
    },
    getLocalTime(n) {
        return new Date(parseInt(n)).toLocaleString().replace(/:\d{1,2}$/,' ');
    },
    getTimeDifference(time) {
        if (time < (60*1000)) {
            this.executionTime = time / 1000 + " s";
            return
        }
        if (time < (60*60*1000)) {
            this.executionTime = time / (1000*60) + " min";
        } else {
            this.executionTime = (time)/(1000*60*60) + " h";
        }
    }
}
